package com.hs.telepass.ui;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.google.gson.JsonSyntaxException;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Result;
import com.hs.teleform.R;
import com.hs.telepass.Constants;
import com.hs.telepass.controller.TaskController;
import com.hs.telepass.controller.task.*;
import com.hs.telepass.manager.*;
import com.hs.telepass.model.Profile;
import com.hs.telepass.model.QrCodeModal;
import com.hs.telepass.model.json.PublicKeyJson;
import com.hs.telepass.model.json.response.FetchPubkeyResponseJson;
import com.hs.telepass.model.json.response.GetOrgInfoResponseJson;
import com.hs.telepass.model.json.response.InitSingouAuthReponseJson;
import com.hs.telepass.model.RepositoryProfile;
import com.hs.telepass.model.json.response.StartResponseItemJson;
import com.hs.telepass.utils.*;
import com.hs.telepass.zxing.camera.CameraManager;
import com.hs.telepass.zxing.control.AmbientLightManager;
import com.hs.telepass.zxing.control.BeepManager;
import com.hs.telepass.zxing.decode.CaptureActivityHandler;
import com.hs.telepass.zxing.decode.InactivityTimer;
import com.hs.telepass.zxing.view.ViewfinderView;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author szw
 * @modified edvard
 * @time 2014-10-3
 */
public final class CaptureFragment extends BaseFragment implements
        SurfaceHolder.Callback {
    public static final String EXTRA_QRCODE_RESULT = "extra_qrcode_result";
    public static final String EXTRA_QRCODE_SOURCE = "extra_qrcode_source";

    public static final String BUNDLE_KEY_SESSIONID = "bundle_key_sessionid";
    public static final String BUNDLE_KEY_RUNTIME_KEY = "bundle_key_runtime_key";
    public static final String BUNDLE_KEY_PUBKEY = "bundle_key_pubkey";
    public static final String BUNDLE_KEY_URL = "bundle_key_url";
    public static final String BUNDLE_PATH_NAME = "bundle_path_name";

    public static final String BUNDLE_KEY_QR = "bundle_key_qr";
    public static final String BUNDLE_KEY_PROFILE = "bundle_key_profile";
    public static final String BUNDLE_KEY_SID = "bundle_key_sid";

    public static final int CONTROL_CAN_OPEN_CAMERA = 0;

    private Context mContext;
    private View mRootView;

    private String mSessionId;
    private String mRuntime_key;
    private String mPublicKey;

    private String mSid;
    private String mQrid;
    private Profile mLastProfile;

    private QrCodeModal mCurrentQrCode;
    private RepositoryProfile mCurrentRepoProfile;

    private Button btn_back;
    private Button btn_torch;
    private boolean isTorchOn = false;
    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private Result savedResultToShow;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private Collection<BarcodeFormat> decodeFormats;
    private Map<DecodeHintType, ?> decodeHints;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private BeepManager beepManager;
    private AmbientLightManager ambientLightManager;
    SurfaceView mSurfaceView;
    /**
     * 相机是否能够重制
     */
    private boolean mCanReOpenCamera = true;

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    private View findViewById(int id) {
        return mRootView.findViewById(id);
    }

    private View inflateAndSetupView(LayoutInflater inflater,
                                     ViewGroup container, Bundle savedInstanceState, int layoutResourceId) {
        mRootView = inflater.inflate(layoutResourceId, container, false);

        return mRootView;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflateAndSetupView(inflater, container, savedInstanceState, R.layout.capture_fragment);
    }

    @Override
    public void onActivityCreated(Bundle icicle) {
        super.onActivityCreated(icicle);

        mContext = getActivity();

        Window window = getActivity().getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        btn_back = (Button) mRootView.findViewById(R.id.btn_back);
        btn_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
        btn_torch = (Button) mRootView.findViewById(R.id.btn_torch);
        btn_torch.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isTorchOn) {
                    isTorchOn = false;
                    btn_torch.setText(R.string.close);
                    cameraManager.setTorch(false);
                } else {
                    isTorchOn = true;
                    btn_torch.setText(R.string.open_flash);
                    cameraManager.setTorch(true);
                }
            }
        });

        hasSurface = false;
        inactivityTimer = new InactivityTimer(getActivity());
        beepManager = new BeepManager(getActivity());
        ambientLightManager = new AmbientLightManager(getActivity());
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onResume() {
        super.onResume();
        restartCamera();
        viewfinderView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                //手动对焦
                if (null != cameraManager && null != cameraManager.getCamera()) {
                    try {
                        cameraManager.getCamera().cancelAutoFocus();
                        cameraManager.startFocus();
                        /*cameraManager.getCamera().cancelAutoFocus();
                        cameraManager.getCamera().autoFocus(new Camera.AutoFocusCallback() {

                            public void onAutoFocus(boolean success, Camera camera) {
                                //TODO 自动对焦
                            }});*/
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
               /* if(mCanReOpenCamera){
                    restartCamera();
                    mCanReOpenCamera = false;
                    mCanOpenHandler.sendEmptyMessageDelayed(CONTROL_CAN_OPEN_CAMERA, 3000);
                }*/
            }
        });
    }

    /**
     * 重启摄像头
     */
    public void restartCamera() {
        //避免摄像头重启太频繁
        if (!mCanReOpenCamera) {
            mCanOpenHandler.sendEmptyMessage(CONTROL_CAN_OPEN_CAMERA);
            return;
        }
        if (null != cameraManager)
            closeCamera();
        cameraManager = new CameraManager(mContext.getApplicationContext());

        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        viewfinderView.setCameraManager(cameraManager);

        handler = null;
        resetStatusView();

        mSurfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = mSurfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
        }

        beepManager.updatePrefs();
        ambientLightManager.start(cameraManager);

        inactivityTimer.onResume();

        decodeFormats = null;
        characterSet = null;
    }

    @Override
    public void onPause() {
        closeCamera();
        super.onPause();
    }

    /**
     * 关闭摄像头
     */
    public void closeCamera() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        ambientLightManager.stop();
        cameraManager.closeDriver();
        if (!hasSurface) {
            mSurfaceView = (SurfaceView) findViewById(R.id.preview_view);
            SurfaceHolder surfaceHolder = mSurfaceView.getHolder();
            surfaceHolder.removeCallback(this);
        }
    }

    @Override
    public void onDestroy() {
        inactivityTimer.shutdown();
        viewfinderView.recycleLineDrawable();
        super.onDestroy();
    }

    @Override
    public IntentFilter getIntentFilter() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(FetchPubkeyTask.ACTION_FETCH_PUBKEY_TASK);
        intentFilter.addAction(StartSingouSessionTask.ACTION_START_SINGOU_SESSION_TASK);
        intentFilter.addAction(InitSingouAuthTask.ACTION_INIT_SINGOU_AUTH_TASK);
        intentFilter.addAction(GetProfileInfoTask.ACTION_GET_PROFILE_INFO_TASK);
        intentFilter.addAction(SendAuthTask.ACTION_SEND_AUTH_TASK);
        intentFilter.addAction(UpdateSessionTask.ACTION_UPDATE_SESSION_TASK);
        intentFilter.addAction(GetOrgInfoTask.ACTION_GET_ORG_INFO);
        intentFilter.addAction(SetDeviceTokenTask.ACTION_SET_DEVICE_TOKEN);
        return intentFilter;
    }

    @Override
    public void handleOnReceive(Intent intent) {
        String action = intent.getAction();
        if (FetchPubkeyTask.ACTION_FETCH_PUBKEY_TASK.equals(action)) {
            handleFetchPubkey(intent);
        } else if (StartSingouSessionTask.ACTION_START_SINGOU_SESSION_TASK.equals(action)) {
            handleStartSession(intent);
        } else if (InitSingouAuthTask.ACTION_INIT_SINGOU_AUTH_TASK.equals(action)) {
            handleInitAuth(intent);
        } else if (GetProfileInfoTask.ACTION_GET_PROFILE_INFO_TASK.equals(action)) {
            handleGetRepoProfile(intent);
        } else if (SendAuthTask.ACTION_SEND_AUTH_TASK.equals(action)) {
            handleSendAuth(intent);
        } else if (UpdateSessionTask.ACTION_UPDATE_SESSION_TASK.equals(action)) {
            handleUpdateSession(intent);
        } else if (GetOrgInfoTask.ACTION_GET_ORG_INFO.equals(action)) {
            handleGetOrgInfo(intent);
        } else if (SetDeviceTokenTask.ACTION_SET_DEVICE_TOKEN.equals(action)) {
            handleSetDeviceToken(intent);
        }
    }

    private void handleFetchPubkey(Intent intent) {
        int event = intent.getIntExtra(TaskController.EXTRA_EVENT,
                TaskController.EVENT_TASK_ERROR);
        switch (event) {
            case TaskController.EVENT_TASK_BEGIN:
                dialogLoading();
                break;
            case TaskController.EVENT_TASK_END:
                dialogDimiss();
                break;
            case TaskController.EVENT_TASK_SUCCEED:
                FetchPubkeyResponseJson fetchJson = (FetchPubkeyResponseJson) intent.getSerializableExtra(TaskController.EXTRA_RESPONSE);
                PublicKeyJson publicKey = fetchJson.getPubkey();
                mPublicKey = publicKey.getPubkey();

                Intent jumpIntent = new Intent(mContext, InputUserInfoActivity.class);

                List<Profile> profileList = ProfilesManager.getInstance().getProfilesByTarget(Constants.SOURCE_TELEFORM, publicKey.getHostname());

                Bundle bundle = new Bundle();
                bundle.putString(CaptureFragment.BUNDLE_KEY_SESSIONID, mSessionId);
                bundle.putString(CaptureFragment.BUNDLE_KEY_RUNTIME_KEY, mRuntime_key);
                bundle.putString(CaptureFragment.BUNDLE_KEY_PUBKEY, mPublicKey);
                bundle.putString(CaptureFragment.BUNDLE_KEY_URL, publicKey.getHostname());
                bundle.putString(CaptureFragment.BUNDLE_PATH_NAME, publicKey.getPathname());

                if (null != profileList && 1 == profileList.size()) {

                    mLastProfile = profileList.get(0);


                    if (true == PreferencesManager.getInstance().getFastLoginSwitch()) {
                        try {
                            TeleformManager.getInstance().updateSession(mSessionId, mLastProfile.getUsername(),
                                    mLastProfile.getPassword(), mPublicKey, mRuntime_key);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {

                        bundle.putSerializable(CaptureFragment.BUNDLE_KEY_PROFILE, mLastProfile);
                        jumpIntent.putExtra(CaptureFragment.EXTRA_QRCODE_RESULT, bundle);
                        jumpIntent.putExtra(CaptureFragment.EXTRA_QRCODE_SOURCE, Constants.SOURCE_TELEFORM);
                        startActivity(jumpIntent);
                        getActivity().overridePendingTransition(R.anim.activity_open, 0);

//                        ToastUtil.showMessageInShort(context, R.string.fetch_public_key_success);
                    }
                } else if (null == profileList || 0 == profileList.size()) {
                    jumpIntent.putExtra(CaptureFragment.EXTRA_QRCODE_RESULT, bundle);
                    jumpIntent.putExtra(CaptureFragment.EXTRA_QRCODE_SOURCE, Constants.SOURCE_TELEFORM);
                    startActivity(jumpIntent);
                    getActivity().overridePendingTransition(R.anim.activity_open, 0);
                } else {
                    jumpIntent.setClass(mContext, MultiUserInfoActivity.class);
                    jumpIntent.putExtra(CaptureFragment.EXTRA_QRCODE_RESULT, bundle);
                    jumpIntent.putExtra(CaptureFragment.EXTRA_QRCODE_SOURCE, Constants.SOURCE_TELEFORM);
                    startActivity(jumpIntent);
                    getActivity().overridePendingTransition(R.anim.activity_open, 0);
                }


                break;
            case TaskController.EVENT_TASK_FAILED:
                dialogDimiss();
                String failrMsg = intent.getStringExtra(TaskController.EXTRA_RESPONSE);
                ToastUtil.showMessageInShort(context, failrMsg);
                restartCamera();
                break;
            case TaskController.EVENT_TASK_ERROR:
                dialogDimiss();
                String errorMsg = intent.getStringExtra(TaskController.EXTRA_RESPONSE);
                ToastUtil.showMessageInShort(context, errorMsg);
                restartCamera();
                break;
            default:
                break;
        }

    }

    private void handleStartSession(Intent intent) {
        int event = intent.getIntExtra(TaskController.EXTRA_EVENT,
                TaskController.EVENT_TASK_ERROR);
        switch (event) {
            case TaskController.EVENT_TASK_BEGIN:
                break;
            case TaskController.EVENT_TASK_END:

                break;
            case TaskController.EVENT_TASK_SUCCEED:
                StartResponseItemJson json = (StartResponseItemJson) intent.getSerializableExtra(TaskController.EXTRA_RESPONSE);
                mQrid = mCurrentQrCode.getI();
                mSid = json.getSid();
                PreferencesManager.getInstance().setAccountId(json.getAccountid());
                try {
                    SingouManager.getInstance().initSingouAuth(mQrid, mSid, mRuntime_key);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case TaskController.EVENT_TASK_FAILED:
                dialogDimiss();
                String msg = intent.getStringExtra(TaskController.EXTRA_RESPONSE);
                //TODO 替换成activity
                showErrorMsgDialog(msg);
                /*ToastUtil.showMessageInLong(mContext, msg);
                restartCamera();*/
                break;
            case TaskController.EVENT_TASK_ERROR:
                dialogDimiss();
                restartCamera();
                break;
            default:
                break;
        }

    }

    private void handleInitAuth(Intent intent) {
        int event = intent.getIntExtra(TaskController.EXTRA_EVENT,
                TaskController.EVENT_TASK_ERROR);
        switch (event) {
            case TaskController.EVENT_TASK_BEGIN:
                break;
            case TaskController.EVENT_TASK_END:
                dialogDimiss();
                break;
            case TaskController.EVENT_TASK_SUCCEED:
                InitSingouAuthReponseJson json = (InitSingouAuthReponseJson) intent.getSerializableExtra(TaskController.EXTRA_RESPONSE);
                if ("waiting".equals(json.getStatus())) {
                    Intent jumpIntent = new Intent();
                    jumpIntent.setClass(getActivity(), InputUserInfoActivity.class);
                    jumpIntent.putExtra(CaptureFragment.EXTRA_QRCODE_SOURCE, Constants.SOURCE_SINGOU);

                    if (null != mCurrentRepoProfile)
                        mCurrentQrCode.setProfile(mCurrentRepoProfile);
                    List<Profile> profileList = ProfilesManager.getInstance().getProfilesByTarget(Constants.SOURCE_SINGOU, mCurrentRepoProfile.getTitle());
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(BUNDLE_KEY_QR, mCurrentQrCode);
                    bundle.putString(BUNDLE_KEY_SID, mSid);
                    bundle.putString(BUNDLE_KEY_RUNTIME_KEY, mRuntime_key);

                    //当不存在登陆记录或者登陆为1时, 进入普通的登陆界面
                    if (null != profileList && 1 == profileList.size()) {

                        mLastProfile = profileList.get(0);

                        if (true == PreferencesManager.getInstance().getFastLoginSwitch() && !StringUtil.isEmpty(mLastProfile.getPassword())) {

                            try {
                                SingouManager.getInstance().sendAuth(mSid, mLastProfile.getUsername(), mLastProfile.getPassword(), mQrid, mRuntime_key);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {

                            bundle.putSerializable(BUNDLE_KEY_PROFILE, mLastProfile);
                            jumpIntent.putExtra(CaptureFragment.EXTRA_QRCODE_RESULT, bundle);
                            startActivity(jumpIntent);

                            getActivity().overridePendingTransition(R.anim.activity_open, 0);
                        }
                    } else if (null == profileList || 0 == profileList.size()) {
                        jumpIntent.putExtra(CaptureFragment.EXTRA_QRCODE_RESULT, bundle);
                        startActivity(jumpIntent);

                        getActivity().overridePendingTransition(R.anim.activity_open, 0);
                    } else {
                        jumpIntent.setClass(getActivity(), MultiUserInfoActivity.class);
                        jumpIntent.putExtra(CaptureFragment.EXTRA_QRCODE_RESULT, bundle);
                        startActivity(jumpIntent);
                        getActivity().overridePendingTransition(R.anim.activity_open, 0);
                    }


                }
                break;
            case TaskController.EVENT_TASK_FAILED:
                dialogDimiss();
                restartCamera();
                break;
            case TaskController.EVENT_TASK_ERROR:
                dialogDimiss();
                restartCamera();
                break;
            default:
                break;
        }

    }

    private void handleGetRepoProfile(Intent intent) {
        int event = intent.getIntExtra(TaskController.EXTRA_EVENT,
                TaskController.EVENT_TASK_ERROR);
        switch (event) {
            case TaskController.EVENT_TASK_BEGIN:
                break;
            case TaskController.EVENT_TASK_END:

                break;
            case TaskController.EVENT_TASK_SUCCEED:
                mCurrentRepoProfile = (RepositoryProfile) intent.getSerializableExtra(TaskController.EXTRA_RESPONSE);
                mCurrentRepoProfile.setServiceId(mCurrentQrCode.getS());
                mCurrentRepoProfile.setServiceName(mCurrentQrCode.getN());
                RepositoryProfilesManager.getInstance().add(mCurrentRepoProfile);
                break;
            case TaskController.EVENT_TASK_FAILED:
                //TODO 时间赶赶的
                /*try {
//                    TaskController.getInstance().getRepositoryProfile(mContext, mCurrentQrCode.getS(), mCurrentQrCode.getN());
                    restartCamera();
                } catch (Exception e) {
                	restartCamera();
                    e.printStackTrace();
                }*/
                break;
            case TaskController.EVENT_TASK_ERROR:
                try {
                    TaskController.getInstance().getRepositoryProfile(mContext, mCurrentQrCode.getS(), mCurrentQrCode.getN());
                    restartCamera();
                } catch (Exception e) {
                    restartCamera();
                    e.printStackTrace();
                }

                break;
            default:
                break;
        }

    }

    private void handleSendAuth(Intent intent) {
        int event = intent.getIntExtra(TaskController.EXTRA_EVENT,
                TaskController.EVENT_TASK_ERROR);
        switch (event) {
            case TaskController.EVENT_TASK_BEGIN:
                break;
            case TaskController.EVENT_TASK_END:

                break;
            case TaskController.EVENT_TASK_SUCCEED:
                restartCamera();
                /**此处用于快速登陆, 顾不用登入数据库*/
                ShortSoundUtil.getInstance().unlock();
                ToastUtil.showMessageInShort(mContext, R.string.auth_success);
                break;
            case TaskController.EVENT_TASK_FAILED:
                restartCamera();
                break;
            case TaskController.EVENT_TASK_ERROR:
                restartCamera();
                ToastUtil.showMessageInShort(mContext, R.string.auth_fail);
                break;
            default:
                break;
        }
    }


    private void handleUpdateSession(Intent intent) {
        int event = intent.getIntExtra(TaskController.EXTRA_EVENT,
                TaskController.EVENT_TASK_ERROR);
        switch (event) {
            case TaskController.EVENT_TASK_BEGIN:
                break;
            case TaskController.EVENT_TASK_END:

                break;
            case TaskController.EVENT_TASK_SUCCEED:
                resetStatusView();
                ShortSoundUtil.getInstance().unlock();
                ToastUtil.showMessageInShort(context, R.string.login_success);
                break;
            case TaskController.EVENT_TASK_FAILED:
                restartCamera();
                String errorMsg = intent.getStringExtra(TaskController.EXTRA_RESPONSE);
                ToastUtil.showMessageInShort(context, errorMsg);
                break;
            case TaskController.EVENT_TASK_ERROR:
                restartCamera();
                break;
            default:
                break;
        }
    }

    private void handleGetOrgInfo(Intent intent) {
        int event = intent.getIntExtra(TaskController.EXTRA_EVENT,
                TaskController.EVENT_TASK_ERROR);
        switch (event) {
            case TaskController.EVENT_TASK_BEGIN:
                break;
            case TaskController.EVENT_TASK_END:

                break;
            case TaskController.EVENT_TASK_SUCCEED:
                GetOrgInfoResponseJson resultJson = intent.getParcelableExtra(TaskController.EXTRA_RESPONSE);
                InputPhoneNumberDialog dialog = new InputPhoneNumberDialog();
                dialog.setTitle(resultJson.getName());
                dialog.setOnCancelClickListener(new InputPhoneNumberDialog.OnCancelClickListerner() {
                    @Override
                    public void onClick() {
                        restartCamera();
                    }
                });
                dialog.setStoreId(resultJson.getStore_id());

                dialog.show(getFragmentManager(), "InputPhoneNumberDialog");
                break;
            case TaskController.EVENT_TASK_FAILED:
                restartCamera();
                String errorMsg = intent.getStringExtra(TaskController.EXTRA_RESPONSE);
                ToastUtil.showMessageInShort(context, errorMsg);
                break;
            case TaskController.EVENT_TASK_ERROR:
                restartCamera();
                break;
            default:
                break;
        }
    }

    private void handleSetDeviceToken(Intent intent) {
        int event = intent.getIntExtra(TaskController.EXTRA_EVENT,
                TaskController.EVENT_TASK_ERROR);
        switch (event) {
            case TaskController.EVENT_TASK_BEGIN:
                dialogLoading(R.string.setting_token);
                break;
            case TaskController.EVENT_TASK_END:
                dialogDimiss();
                break;
            case TaskController.EVENT_TASK_SUCCEED:
                restartCamera();
                ToastUtil.showMessageInShort(context, R.string.set_token_success);
                break;
            case TaskController.EVENT_TASK_FAILED:
                restartCamera();
                String errorMsg = intent.getStringExtra(TaskController.EXTRA_RESPONSE);
                ToastUtil.showMessageInShort(context, errorMsg);
                break;
            case TaskController.EVENT_TASK_ERROR:
                ToastUtil.showMessageInShort(context, R.string.num_wrong);
                restartCamera();
                break;
            default:
                break;
        }
    }



	/*@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_CAMERA:// ��������
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}*/

    private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
        if (handler == null) {
            savedResultToShow = result;
        } else {
            if (result != null) {
                savedResultToShow = result;
            }
            if (savedResultToShow != null) {
                Message message = Message.obtain(handler,
                        R.id.decode_succeeded, savedResultToShow);
                handler.sendMessage(message);
            }
            savedResultToShow = null;
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    /**
     * 处理扫描后的结果
     */
    public void handleDecode(Result rawResult) {
        //记录与设置界面对二维码不进行任何处理
        if (MainActivity.TAB_CAMERA_ITEM != ((MainActivity) getActivity()).getCurrentItem()) {
            restartCamera();
            return;
        }
        inactivityTimer.onActivity();
        ShortSoundUtil.getInstance().scanPlay();
//		beepManager.playBeepSoundAndVibrate();

        String msg = rawResult.getText();
        if (msg == null || "".equals(msg)) {
            msg = "test";
        }

        //判断是否社团的二维码
        if (OrganiztionManageer.getInstance().isOrgQrCode(msg)) {
            TaskController.getInstance().getOrgInfo(context, OrganiztionManageer.getInstance().getMeetingId(msg));
            return;
        }

        if (true == PreferencesManager.getInstance().getLoginPwdSwitch())
            showInputSingouPswDialog(msg);
        else
            startTryLogin(msg);

    }

    private void startTryLogin(String msg) {
        if (UrlUtil.isUrl(msg)) {
            showUrlDialog(msg);
            return;
        }
        //用以判断二维码来源
        String testArray[] = msg.split(":");

        if (1 != testArray.length) {
            /**singou扫描*/
            try {
                msg = cutWrongMsg(msg);
                mCurrentQrCode = JsonUtil.fromJson(msg, QrCodeModal.class);
                mRuntime_key = RunTimeKeyUtil.getUUIDByRules(RunTimeKeyUtil.getUUID());


                if (!RepositoryProfilesManager.getInstance().hasSame(mCurrentQrCode.getS(), mCurrentQrCode.getN())) {
                    TaskController.getInstance().getRepositoryProfile(mContext, mCurrentQrCode.getS(), mCurrentQrCode.getN());

                } else {
                    mCurrentRepoProfile = RepositoryProfilesManager.getInstance().get(mCurrentQrCode.getS(), mCurrentQrCode.getN());
                }

                String accountId = PreferencesManager.getInstance().getAccountId();
                String password = PreferencesManager.getInstance().getPasswordKey();
                SingouManager.getInstance().startSingouSession(accountId, password, mRuntime_key, false);
            } catch (JsonSyntaxException e) {
                ToastUtil.showMessageInShort(mContext, R.string.tip_qrcode_invalid);
                restartCamera();
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            /**teleform扫描*/
            mSessionId = msg;
            mRuntime_key = RunTimeKeyUtil.getUUIDByRules(RunTimeKeyUtil.getUUID());
            try {
                TeleformManager.getInstance().fetchPublicKey(mRuntime_key, mSessionId);
            } catch (Exception e) {
                restartCamera();
                e.printStackTrace();
            }
        }
    }

    /**
     * 截取扫描二维码后有用的部分
     */
    private String cutWrongMsg(String msgCode) {
        int index = msgCode.lastIndexOf("}");
        String result = msgCode;
        if (0 < index) {
            result = result.substring(0, index + 1);
        }

        return result;
    }

    private void showInputSingouPswDialog(final String msg) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View dialogView = inflater.inflate(R.layout.security_profile_dialog, null);
        final EditText editText = (EditText) dialogView.findViewById(R.id.proifle_username);

        /**下面的写法能够控制dialog消失*/
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(
                getString(R.string.title_input_password))
                .setIcon(android.R.drawable.ic_dialog_info)
                .setView(dialogView)
                .setNegativeButton("Cancel", null)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });

        final AlertDialog dialog = builder.create();
        dialog.show();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String realPassword = PreferencesManager.getInstance().getPasswordKey();
                String password = editText.getText().toString();
                if (StringUtil.isEmpty(password) || !realPassword.equals(password)) {
                    restartCamera();
                    ToastUtil.showMessageInShort(mContext, R.string.tip_input_right);
                } else {
                    startTryLogin(msg);
                }
                dialog.dismiss();
            }
        });
        ;

    }


    public void showErrorMsgDialog(String errorMsg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(getString(R.string.error_msg_title))
                .setIcon(android.R.drawable.ic_dialog_info)
                .setMessage(errorMsg)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        restartCamera();
                    }
                })
                .create()
                .show();
    }

    private void showUrlDialog(final String msg) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.dialog_title_not_singou_qr)
                .setMessage(R.string.dialog_content_not_singou_qr)
                .setNegativeButton(R.string.no, null)

                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

        final AlertDialog dialog = builder.create();
        dialog.show();

        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(msg);
                intent.setData(content_url);
                startActivity(intent);
                dialog.dismiss();

            }
        });
        dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                restartCamera();
            }
        });
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            return;
        }
        if (cameraManager.isOpen()) {
            return;
        }
        try {
            cameraManager.openDriver(surfaceHolder);
            if (handler == null) {
                handler = new CaptureActivityHandler(this, decodeFormats,
                        decodeHints, characterSet, cameraManager);
            }
            decodeOrStoreSavedBitmap(null, null);
        } catch (IOException ioe) {
            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            displayFrameworkBugMessageAndExit();
        }
    }

    /**
     * 不显示任何错误信息
     */
    private void displayFrameworkBugMessageAndExit() {
//		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
//		builder.setTitle("����");
//		builder.setMessage("��Ǹ�����������⣬�������Ҫ�����豸");
//		builder.setPositiveButton("ȷ��", new FinishListener(getActivity()));
//		builder.setOnCancelListener(new FinishListener(getActivity()));
//		builder.show();
    }

    public void restartPreviewAfterDelay(long delayMS) {
        if (handler != null) {
            handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
        }
        resetStatusView();
    }

    private void resetStatusView() {
        viewfinderView.setVisibility(View.VISIBLE);
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    private Handler mCanOpenHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CONTROL_CAN_OPEN_CAMERA:
                    mCanReOpenCamera = true;
                    break;
            }
        }
    };
}
